//
//  PersonInfoViewController.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/8.
//

#import "PersonInfoViewController.h"
#import "PersonInfoTableViewCell.h"
#import "SuoShuQiYeViewController.h"
#import "CreateQiYeViewController.h"
#import "CitiesListView.h"
#import "LoginPageViewController.h"
@interface PersonInfoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray  *dataAry;
@property (nonatomic, strong) NSString        *userName;
@property (nonatomic, strong) NSString        *carNum;
@property (nonatomic, strong) NSString        *workAddress;
@property (nonatomic, copy) NSString  *workAddressStr;
@property (nonatomic, strong) NSDictionary *dict;

@end

@implementation PersonInfoViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self createRightButtonItem];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layoutCustomNav:self.view title:@"完善个人资料"];

    self.dataAry = [NSMutableArray arrayWithArray:@[@"真实姓名",@"身份证号",@"工作地点"]];
    [self createTableView];
}



-(void)createTableView{
    self.tableView = [[UITableView  alloc] initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, B_HEIGHT - LL_StatusBarAndNavigationBarHeight - LL_TabbarSafeBottomMargin)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:[PersonInfoTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[PersonInfoTableViewCell reuseIdentifier]];
    [self.view addSubview:self.tableView];
    
    }
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataAry.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
     return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonInfoTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:[PersonInfoTableViewCell reuseIdentifier]];
    if (!cell) {
        cell=[[PersonInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[PersonInfoTableViewCell reuseIdentifier]];
    }
    cell.selectionStyle= UITableViewCellSelectionStyleNone;
    cell.nameLb.text = self.dataAry[indexPath.row];
    cell.selectPath = indexPath.row;
    cell.contentTF.userInteractionEnabled = indexPath.row != 2;
    switch (indexPath.row) {
        case 0:
        {
            [ChineseNotificationHelp ChineseNotificationHelpShareWithTextFiled:cell.contentTF];
            if (self.userName.length == 0) {
                cell.contentTF.placeholder = @"请输入真实姓名";
            } else {
                cell.contentTF.text = self.userName;
            }
        }
        break;
        case 1:
        {
            if (self.carNum.length == 0) {
                cell.contentTF.placeholder=@"请输入身份证号";
            } else {
                cell.contentTF.text=self.carNum;
            }
        }
        break;
        case 2:
        {
            if (self.workAddress.length== 0) {
                cell.contentTF.placeholder = @"请输入工作地点";
            } else {
                cell.contentTF.text=self.workAddressStr;
            }
        }
        break;
        default:
            break;
    }
    [cell setCurrentValueBlock:^(NSString * _Nonnull contentText, NSInteger selectPath) {
        if (selectPath == 0){
            self.userName = contentText;
        }else if (selectPath == 1){
            self.carNum = contentText;
        } else {
            self.workAddress = contentText;
        }
    }];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        [self chooseAddress];
    }
}
///城市选择器
- (void)chooseAddress {
    CitiesListView *view = [[CitiesListView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    [[AppDelegate shareDelegete].window addSubview:view];
    WEAKSELF
    [view setPACStr:^(NSString * _Nonnull PACStr, NSString * _Nonnull codeStr, NSString * _Nonnull addressArrStr) {
        NSArray *city = [codeStr componentsSeparatedByString:@","];
        NSArray *cityName = [addressArrStr componentsSeparatedByString:@","];
        self.workAddressStr = [cityName componentsJoinedByString:@""];
        self.workAddress = city.lastObject;
        
        [self.tableView reloadData];
    }];
}
#pragma mark - 获取三级联动的数据源
- (NSArray <BRResultModel *>*)getLinkag3DataSource:(NSDictionary *)dic {
    NSMutableArray *allRegionModelArr = [[NSMutableArray alloc]init];
    // 省
    NSArray *provinceArr = dic[@"children"];
    for (NSInteger i = 0; i < provinceArr.count; i++) {
        BRResultModel *model = [[BRResultModel alloc]init];
        model.parentKey = @"-1";
        model.parentValue = @"";
        model.key = [NSString stringWithFormat:@"%@", provinceArr[i][@"id"]];
        model.value = provinceArr[i][@"text"];
        [allRegionModelArr addObject:model];
    }
    // 市
    NSArray *cityArr = dic[@"children"][@"children"];
    for (NSInteger i = 0; i < cityArr.count; i++) {
        BRResultModel *model = [[BRResultModel alloc]init];
        model.parentKey = [NSString stringWithFormat:@"%@", cityArr[i][@"id"]];
        model.parentValue = @"";
        model.key = [NSString stringWithFormat:@"%@", cityArr[i][@"id"]];
        model.value = cityArr[i][@"text"];
        [allRegionModelArr addObject:model];
    }
    // 区
    NSArray *areaArr = dic[@"children"][@"children"];
    for (NSInteger i = 0; i < areaArr.count; i++) {
        BRResultModel *model = [[BRResultModel alloc]init];
        model.parentKey = [NSString stringWithFormat:@"%@", areaArr[i][@"id"]];;
        model.parentValue = @"";
        model.key = [NSString stringWithFormat:@"%@", areaArr[i][@"id"]];
        model.value = areaArr[i][@"text"];
        [allRegionModelArr addObject:model];
    }
    
    return [allRegionModelArr copy];
}
- (void)pop{
    [[MSStorageUtils shareInstance] userDefaultSave:@"NO" withKey:USER_DEFAULT_KEY_MEMBER_IsLogin];
    [[SDWebImageDownloader sharedDownloader] cancelAllDownloads];
    [[YTKNetworkAgent sharedAgent] cancelAllRequests];
    [SSKeyChainMgr delLoginToken];
    [YLUserMgr deleteUser];
    LoginPageViewController *pageVC = [[LoginPageViewController  alloc] init];
    UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:pageVC];
    UIWindow  *mainWindow = [BaseViewController getCurrentWindow];
    [mainWindow setRootViewController:navigationVC];
    
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
    } seq:1];
    
    showAlert(@"退出成功");
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [PersonInfoTableViewCell cellHeight];
}

-(void)createRightButtonItem{
    
    UIButton *eduitButton = [UIButton buttonWithType:UIButtonTypeCustom];
     eduitButton.frame = CGRectMake(ScreenWidth-100, KStatuesBarHeight, 80, 30);
    [eduitButton setTitle:@"下一步" forState:UIControlStateNormal];
     eduitButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(13.0)];
     eduitButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [eduitButton setTitleColor:White_Color forState:UIControlStateNormal];
    eduitButton.backgroundColor = mainColor;
    [eduitButton createBordersWithColor:nil withCornerRadius:5.0 andWidth:0];
    [eduitButton addTarget:self action:@selector(EduitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:eduitButton];
}

-(void)EduitButtonClick{
    [self CommitPersonInfo];
}

-(void)CommitPersonInfo{
    [self.view endEditing:YES];
    if (self.userName.length == 0) {
        showAlert(@"请输入真实姓名");
        return;
    }
    if (self.carNum.length == 0) {
        showAlert(@"请输入身份证号");
        return;
    }
    if (![self.carNum isCorrect:self.carNum]){
        showAlert(@"身份证格式不正确");
        return;
    }
    if (self.workAddress.length== 0) {
        showAlert(@"请输入工作地址");
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"1" forKey:@"cmd"];
    [params setObject:self.userName forKey:@"realName"];
    [params setObject:self.carNum forKey:@"carNum"];
    [params setObject:self.workAddress forKey:@"workAddress"];
    
    
    [MSNetworkManager postRevertUrl:Post_UpDateUserInfo params:params success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if (isSuccess) {
            NSDictionary  *objects = resonseObj[@"sysUser"];
            [self saveUserInfo:objects];
             YLUserInfo * info = [YLUserMgr fetchUser];
             if (info == nil) info = [[YLUserInfo alloc] init];
             [YLUserMgr saveUser:info];
             SuoShuQiYeViewController *VC = [[SuoShuQiYeViewController alloc] init];
             VC.isFromeLogin = self.isFromeLogin;
             [self pushToNextController:VC];
        }
        
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    

}

-(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    } else {
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

@end
